package com.cn.hjsj.util.md5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
	public final static String GetMD5Code(StringBuffer data) {
		 try {
			 MessageDigest md = MessageDigest.getInstance("MD5");
			 md.update(data.toString().getBytes());
			 byte b[] = md.digest();

			 int i;

			 StringBuffer buf = new StringBuffer("");
			 for (int offset = 0; offset < b.length; offset++) {
			 i = b[offset];
			 if(i<0) i+= 256;
			 if(i<16)
			 buf.append("0");
			 buf.append(Integer.toHexString(i));
			 }
			 return buf.toString().toUpperCase();
			 
			 } catch (NoSuchAlgorithmException e) {
			 // TODO Auto-generated catch block
				 return null;
			 }
		 }

	public final static String GetMD5Code(String data) {
		try {
			byte[] btInput = data.getBytes("UTF-8");
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(btInput);
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if(i<0) i+= 256;
				if(i<16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString().toUpperCase();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
		}
	}

	public final static String GetMD5_16Code(String data) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(data.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if(i<0) i+= 256;
				if(i<16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString().toUpperCase().substring(8,24);

		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}
}
